var express = require('express');
var router = express.Router();
const bcrypt = require('bcrypt-nodejs');

const CmmuseumModel = require('../db/CmmuseumModel');
const Fun = require("../middlewares/Fun")
const moment = require('moment');
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}
const UserModel = require('../db/UserModel');//用户模型
const RoleModel = require('../db/RoleModel');//角色模型
/***
 *  list 列表
 *  one 查找单独门店
 *  save 创建门店
 *  update 更新门店信息
 *  delete 删除门店
 */

// 保存门店

// 密码需要加密
router.post('/hadnamed', function (req, res, next) {
    if (!req.body.name) {
        return res.json({ code: 201, mes: '缺少必填信息！' });
    }

    CmmuseumModel.findOne({ name: req.body.name }).then((data) => {
        if (data) {
            return res.json({ code: 201, mes: '该名称已经存在！' });
        } else {
            return res.json({ code: 200, mes: '该名称可用！' });
        }
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' })
    });

});
router.post('/alreadyregister', function (req, res, next) {
    if (!req.body.managerphone) {
        return res.json({ code: 201, mes: '缺少必填信息！' });
    }

    CmmuseumModel.findOne({ managerphone: req.body.managerphone }).then((data) => {
        if (data) {
            return res.json({ code: 201, mes: '该电话号码已经存在！' });
        } else {
            return res.json({ code: 200, mes: '该电话号码可用！' });
        }
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' })
    });

});
router.post('/save', function (req, res, next) {
    let { name, type, address, starttime,
        endtime, limitnumber, managername,
        managerphone, managersex, managercardid,
        manageremail, manageraccount, managerpassword, birthday, jurisdiction } = req.body;
    if (!name || !type || !address || !starttime || !endtime || !limitnumber || !managername || !managercardid || !managerpassword || !managersex || !jurisdiction) {
        return res.json({
            code: 201,
            mes: "缺少必要参数."
        })
    }
    // 获取条件
    let user = req.user;
    let pare;
    const cmmuseum = new CmmuseumModel(req.body);
    cmmuseum.managerpassword = bcrypt.hashSync(req.body.password); // 默认密码
    CmmuseumModel.findOne({ managerphone: req.body.managerphone }).then((data) => {
        if (!data) {
            return CmmuseumModel.find({ name: req.body.name }).then((cmmuseums) => {
                if (cmmuseums.length != 0) { return res.json({ code: 201, mes: '店铺名称已经存在' }); }
                else {
                    return cmmuseum.save().then((cmmuseum) => {
                        pare = {
                            id: user._id,
                            name: user.name,
                            roles: user.role,
                            ip: req.ip.replace(/::ffff:/, ''),
                            time: now(),
                            Operationcontent: "新增门店成功"
                        };
                        let department = [];
                        department.push(cmmuseum._id)
                        let obj = {
                            name: managername,
                            sex: managersex,
                            birthday: birthday || "",
                            phone: managerphone,
                            post: '全职',
                            role: null,
                            department: [],
                            shop: department,
                            papers: "1",
                            IDcard: managercardid,
                            email: manageremail || null,
                            jurisdiction: jurisdiction,
                            commissionproject: '0&0&0',
                            password: bcrypt.hashSync(managerpassword),
                            state: '启用'
                        };
                        return RoleModel.findOne({ name: "超级管理员" }).then(superrole => {
                            obj.role = superrole._id;
                            let doctor = new UserModel(obj);
                            return doctor.save().then(data => {
                                Fun.saveLog(pare);
                                return res.json({ code: 200, mes: '创建门店成功！' })
                            });
                        });
                    }).catch(() => {
                        pare.time = now();
                        pare.Operationcontent = "新增门店失败";
                        Fun.saveLog(pare);
                        return res.json({ code: 201, mes: '发生意外错误！' })
                    })
                }
            }).catch(() => {
                return res.json({ code: 201, mes: '发生意外错误！' })
            });
        } else {
            return res.json({ code: 201, mes: '管理员手机号码已经存在！' });
        }
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' })
    });
});

/**
 * 
 * 
 *
 * 
 */


// 更新门店信息
router.post('/update', function (req, res, next) {
    // 更改密码的判断需要额外处理
    const set = req.body;
    const id = req.body.id;
    let user = req.user;
    CmmuseumModel.findById(id).then(
        (cmmuseum) => {
            if (cmmuseum == null) { return res.json({ code: 201, mes: '传入id错误' }); }
            else {
                return CmmuseumModel.update({ _id: id }, { $set: set }).then(
                    () => { Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "更新门店信息成功"); return res.json({ code: 200, mes: '更改成功' }); }
                ).catch(() => {
                    Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "更新门店信息失败");
                    return res.json({ code: 201, mes: '更改失败！' })
                })
            }
        }
    ).catch(function () {
        return res.json({ code: 201, mes: '修改信息出错' });
    });
});
// 查找所有门店
router.get('/list', function (req, res, next) {
    CmmuseumModel.find().then((cmmuseums) => {
        return res.json({ code: 200, cmmuseums });
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});
// 查找指定门店
router.get('/one/:id', function (req, res, next) {
    const id = req.params.id;
    CmmuseumModel.findById(id).then((cmmuseum) => {
        return res.json({ code: 200, cmmuseum });
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});

//index.页面获取门店
router.get('/initlist', function (req, res, next) {
    CmmuseumModel.find({}, { name: 1, type: 1 }).then((cmmuseums) => {
        return res.json({ code: 200, cmmuseums });
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});


module.exports = router;
